package com.lottery.im.module.contact.presenter;

import android.app.Activity;
import com.lottery.im.base.BaseFragmentPresenter;
import com.lottery.im.module.contact.view.ShipManageMessageView;
import com.lottery.im.module.tim.event.FriendshipEvent;
import com.lottery.im.module.tim.event.MessageEvent;
import com.lottery.im.module.tim.presenter.FriendshipManagerPresenter;
import com.lottery.im.module.tim.presenter.GroupManagerPresenter;
import com.lottery.im.module.tim.viewfeatures.FriendshipMessageView;
import com.lottery.im.module.tim.viewfeatures.GroupManageMessageView;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.group.TIMGroupPendencyItem;
import com.tencent.imsdk.ext.sns.TIMFriendFutureItem;
import com.tencent.imsdk.ext.sns.TIMFriendResult;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.android.FragmentEvent;
import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class ShipManageMessagePresenter extends BaseFragmentPresenter<ShipManageMessageView>
    implements
    FriendshipMessageView, GroupManageMessageView, Observer {

  private FriendshipManagerPresenter mFriendshipManagerPresenter;
  private GroupManagerPresenter mGroupManagerPresenter;

  public ShipManageMessagePresenter(Activity activity,
      ShipManageMessageView iView,
      LifecycleProvider<FragmentEvent> provider) {
    super(activity, iView, provider);
  }

  public void initManagerPresenter() {
    mFriendshipManagerPresenter = new FriendshipManagerPresenter(this);
    mFriendshipManagerPresenter.getFriendshipMessage();

    mGroupManagerPresenter = new GroupManagerPresenter(this);
    mGroupManagerPresenter.getGroupManageMessage(1000);

    FriendshipEvent.getInstance().addObserver(this);
    // 群验证 消息 是属于 系统消息
    MessageEvent.getInstance().addObserver(this);
  }

  /*
   * 好友验证操作
   * id 用户ID
   * type 1 同意 2 拒绝
   * */
  public void setFriendRequest(String id, int type) {
    iView.showLoadingDialog();
    if (type == 1) {
      FriendshipManagerPresenter.acceptFriendRequest(id, new TIMValueCallBack<TIMFriendResult>() {
        @Override
        public void onError(int i, String s) {
          if (null == iView) return;
          iView.showToast("操作失败");
          iView.cancelLoadingDialog();
        }

        @Override
        public void onSuccess(TIMFriendResult timFriendResult) {
          iView.cancelLoadingDialog();
        }
      });
    } else {
      FriendshipManagerPresenter.refuseFriendRequest(id, new TIMValueCallBack<TIMFriendResult>() {
        @Override
        public void onError(int i, String s) {
          if (null == iView) return;
          iView.showToast("操作失败");
          iView.cancelLoadingDialog();
        }

        @Override
        public void onSuccess(TIMFriendResult timFriendResult) {
          // 拒绝的成功，不会收到通知，这边需要手动刷新
          if (null != mFriendshipManagerPresenter) {
            mFriendshipManagerPresenter.getFriendshipMessage();
          }
          if (null == iView) return;
          iView.cancelLoadingDialog();
        }
      });
    }
  }

  /*
   * 加群验证操作
   * id 用户ID
   * type 1 同意 2 拒绝
   * */
  public void setGroupRequest(TIMGroupPendencyItem futureItem, int type) {
    iView.showLoadingDialog();
    if (type == 1) {

      futureItem.accept(null, new TIMCallBack() {
        @Override public void onError(int i, String s) {
          if (i == 10013) {
            //已经是群成员
            if (null == iView) return;
            iView.showToast("已经是群成员");
            if (null != mGroupManagerPresenter) {
              mGroupManagerPresenter.getGroupManageMessage(1000);
            }
          } else {
            if (null == iView) return;
            iView.showToast("操作失败");
          }
          if (null == iView) return;
          iView.cancelLoadingDialog();
        }

        @Override public void onSuccess() {
          if (null != mGroupManagerPresenter) {
            mGroupManagerPresenter.getGroupManageMessage(1000);
          }
          if (null == iView) return;
          iView.cancelLoadingDialog();
        }
      });
    } else {

      futureItem.refuse(null, new TIMCallBack() {
        @Override public void onError(int i, String s) {
          if (null == iView) return;
          iView.showToast("操作失败");
          if (null != mGroupManagerPresenter) {
            mGroupManagerPresenter.getGroupManageMessage(1000);
          }
          if (null == iView) return;
          iView.cancelLoadingDialog();
        }

        @Override public void onSuccess() {
          // 拒绝的成功，不会收到通知，这边需要手动刷新
          if (null != mGroupManagerPresenter) {
            mGroupManagerPresenter.getGroupManageMessage(1000);
          }
          if (null == iView) return;
          iView.cancelLoadingDialog();
        }
      });
    }
  }

  /**
   * 获取好友关系链管理最后一条系统消息的回调
   *
   * @param message 最后一条消息
   * @param unreadCount 未读数
   */
  @Override
  public void onGetFriendshipLastMessage(TIMFriendFutureItem message, long unreadCount) {

  }

  /**
   * 获取好友关系链管理最后一条系统消息的回调
   *
   * @param message 消息列表
   */
  @Override
  public void onGetFriendshipMessage(List<TIMFriendFutureItem> message) {

    if (message != null) {
      if (null != mFriendshipManagerPresenter) {
        if (null == iView) return;
        iView.refreshFriendAdapter(message);
      }
      if (message.size() != 0) {
        if (null != mFriendshipManagerPresenter) {
          // 已读上报
          mFriendshipManagerPresenter.readFriendshipMessage(message.get(0).getAddTime());
        }
      }
    }
  }

  @Override
  public void onGetGroupManageLastMessage(TIMGroupPendencyItem message, long unreadCount) {

  }

  @Override public void onGetGroupManageMessage(List<TIMGroupPendencyItem> message) {
    if (message != null) {
      if (null != mGroupManagerPresenter) {
        if (null == iView) return;
        iView.refreshGroupAdapter(message);
      }
    }
  }

  @Override public void update(Observable observable, Object data) {

    if (observable instanceof FriendshipEvent) {
      FriendshipEvent.NotifyCmd cmd = (FriendshipEvent.NotifyCmd) data;
      switch (cmd.type) {
        case ADD_REQ:
        case DEL:
        case ADD:
          if (null != mFriendshipManagerPresenter) {
            mFriendshipManagerPresenter.getFriendshipMessage();
          }
          break;
      }
    } else if (observable instanceof MessageEvent) {
      if (data instanceof TIMMessage) {
        TIMMessage msg = (TIMMessage) data;
        if (msg == null) {
          return;
        }
        if (msg.getConversation().getType() == TIMConversationType.System) {
          if (null != mGroupManagerPresenter) {
            // 已读上报
            GroupManagerPresenter.readGroupManageMessage(Calendar.getInstance().getTimeInMillis(),
                new TIMCallBack() {
                  @Override
                  public void onError(int i, String s) {
                  }

                  @Override
                  public void onSuccess() {
                  }
                });
            mGroupManagerPresenter.getGroupManageMessage(1000);
          }
          return;
        }
      }
    }
  }

  /*
   * 获取用户信息（主要是由于好友验证的时候本身返回的对方信息是没有头像的）
   * */
  public void getUsersProfile(final int type, List<String> ids) {
    TIMFriendshipManager.getInstance()
        .getUsersProfile(ids, new TIMValueCallBack<List<TIMUserProfile>>() {
          @Override public void onError(int i, String s) {
          }

          @Override public void onSuccess(List<TIMUserProfile> timUserProfiles) {
            if (null == iView) return;
            iView.getUsersProfileSuccess(type, timUserProfiles);
          }
        });
  }

  public void onDestroy() {
    MessageEvent.getInstance().deleteObserver(this);
    FriendshipEvent.getInstance().deleteObserver(this);
    mFriendshipManagerPresenter = null;
    mGroupManagerPresenter = null;
  }
}
